package com.dylan.历史.算法;

import com.dylan.历史.util.LogUtil;

/**
 * Created by Dylan on 2018/10/23.
 */
public class 基础_查找_二分查找 {

    public static void main(String[] args) {
        LogUtil.info(binarySearch(new int[]{1, 2, 3, 5, 7, 9, 12}, 7));
        LogUtil.info(binarySearch(new int[]{1, 2, 3, 5, 7, 9, 12}, 8));
    }

    /**
     * 二分查找算法
     */
    static int binarySearch(int[] arr, int x) {
        int l = 0;
        int r = arr.length - 1;
        int m;
        while (l <= r) {
            m = (l + r) / 2;
            if (arr[m] == x) {
                return m;
            } else if (arr[m] > x) {
                r = m - 1;
            } else {
                l = m + 1;
            }
        }
        return -1;
    }
}
